package com.cartoonrabbit.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cartoonrabbit.pojo.EarlyRecord;
import com.cartoonrabbit.pojo.EarlyUser;
import com.cartoonrabbit.service.IEarlyRecordService;
import com.cartoonrabbit.service.IEarlyUserService;
import com.cartoonrabbit.vo.RespBean;
import com.cartoonrabbit.vo.RespPageBean;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiuTeng
 * @since 2023-01-17
 */
@RestController
@RequestMapping("/early/user")
public class EarlyUserController {

    @Autowired
    private IEarlyUserService earlyUserService;
    @Autowired
    private IEarlyRecordService earlyRecordService;

    @ApiOperation(value = "获取用户早起打卡信息")
    @GetMapping("/info")
    @PreAuthorize("@ss.permitAll()")
    public RespBean getUserInfo(Principal principal){
        if (principal==null){
            return new RespBean(401,"未登录",null);
        }
        EarlyUser byId = earlyUserService.getById(principal.getName());
        if (byId==null){
            byId=new EarlyUser();
            byId.setUserId(principal.getName());
            earlyUserService.save(byId);
        }
        return RespBean.success("SUCCESS",byId);
    }

    @ApiOperation(value = "获取用户早起打卡明细")
    @GetMapping("/recordList")
    @PreAuthorize("@ss.permitAll()")
    public RespBean recordList(@RequestParam(value = "currentPage",defaultValue = "1") Integer currentPage,
                               @RequestParam(value = "size",defaultValue = "10") Integer size,
                               Principal principal){
        if (principal==null){
            return new RespBean(401,"未登录",null);
        }
        Page page = new Page(currentPage, size);
        Page<EarlyRecord> earlyRecordPage=earlyRecordService.page(page,new QueryWrapper<EarlyRecord>().eq("user_id",principal.getName()).orderByDesc("create_time"));
        RespPageBean respPageBean = new RespPageBean();
        respPageBean.setData(earlyRecordPage.getRecords());
        respPageBean.setSize(earlyRecordPage.getSize());
        respPageBean.setCurrentPage(earlyRecordPage.getCurrent());
        respPageBean.setTotal(earlyRecordPage.getTotal());
        return RespBean.success("SUCCESS",respPageBean);
    }

}
